package com.xielx.mynovel.client;

import com.xielx.httpclikent.MyHttpClient;
import com.xielx.httpclikent.bean.MyHttpGet;
import com.xielx.mynovel.ResourceTable;
import com.xielx.mynovel.slice.MainAbilitySlice;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.agp.components.webengine.WebView;
import org.jsoup.internal.StringUtil;

public class QiMaoClient {
    private final static String DOMAIN = "https://www.qimao.com";
    private static String uc;
    private static long expireTime = -1;

    public static void doGet(AbilitySlice slice, String uri, MyHttpClient.CallBack callBack){
        if (StringUtil.isBlank(uc)||expireTime < System.currentTimeMillis()) {
            init(slice);
        }
        MyHttpClient client = MyHttpClient.getInstance(slice);
        MyHttpGet get = new MyHttpGet(DOMAIN+uri);
        get.addHeader("Cookie",uc);
        client.asyncDoRequest(get, callBack);
    }

    public synchronized static void init(AbilitySlice slice) {
        if (expireTime > System.currentTimeMillis()) {
            return;
        }
        //必须要在UI专有的线程中进行UI的更新操作
        MyHttpClient client = MyHttpClient.getInstance(slice);
        MyHttpGet post = new MyHttpGet(DOMAIN);
        client.asyncDoRequest(post, resp -> {
            String content = new String(resp.getContent());
            if (200 != resp.getHttpCode()) {
                slice.getUITaskDispatcher().asyncDispatch(() ->
                    ((Text) slice.findComponentById(ResourceTable.Id_msgText)).setText(content));
            }
            slice.getUITaskDispatcher().asyncDispatch(() -> {
                DirectionalLayout layout = (DirectionalLayout) slice.findComponentById(ResourceTable.Id_htmlLayout);
                WebView webView = new WebView(slice);
                webView.setWidth(DependentLayout.LayoutConfig.MATCH_CONTENT);
                webView.setHeight(DependentLayout.LayoutConfig.MATCH_CONTENT);
                webView.getWebConfig().setJavaScriptPermit(true);
                String data = content.replace("setTimeout('\\x72\\x65\\x6c\\x6f\\x61\\x64\\x28\\x61\\x72\\x67\\x32\\x29',0x2);", "getResult.call(arg2);");
                webView.addJsCallback("getResult", msg -> {
                    uc = "acw_sc__v2="+msg+";";
                    expireTime = System.currentTimeMillis()+1800*1000;
                    slice.present(new MainAbilitySlice(),new Intent());
                    return msg;
                });
                webView.load(data, "text/html", false);
                layout.addComponent(webView);
            });
        });
    }

}
